//
//  XinJianKeHuViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/2.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "XinJianKeHuViewController.h"
#import "DiTuXuanDianViewController.h"
#import "BRStringPickerView.h"
#import "BRAddressPickerView.h"
#import "XinJianKeHuTableViewCell.h"
#import "XinJianKeHuWenBenYuTableViewCell.h"
#import "BRDatePickerView.h"
@interface XinJianKeHuViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSMutableArray *dataSource;
    NSDictionary *keHuInfoDictionary;
    NSString *address;
    NSArray *lanHaiArray;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;


@property (nonatomic,strong) NSArray *addressSelectIndexs;

@end

@implementation XinJianKeHuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    if(_customerId.length > 0){
        self.customNavBar.title = @"编辑";
    }else{
        self.customNavBar.title = @"新建客户";
      
    }
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"XinJianKeHuTableViewCell" bundle:nil] forCellReuseIdentifier:@"XinJianKeHuTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"XinJianKeHuWenBenYuTableViewCell" bundle:nil] forCellReuseIdentifier:@"XinJianKeHuWenBenYuTableViewCell"];
    

   
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    _topSpace.constant = NavaBarHeight;
    _bottomSpace.constant = ScreenBottom+20;
    
    
    //获取创建客户的条件
//    [self huoQuChangJianTiaoJian];
    
    //获取是否有蓝海
    [self huoQuShiFouYouLanHai];
}
//获取是否有蓝海
- (void)huoQuShiFouYouLanHai{
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmCustomerPool/queryBluePoolNameListByUser" andParas:nil andShowHud:NO andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            lanHaiArray = [info objectForKey:@"data"];
            if (lanHaiArray.count > 0) {
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
                [dataDic setValue:@"个人库" forKey:@"poolName"];
                NSMutableArray *array = [NSMutableArray arrayWithArray:lanHaiArray];
                [array insertObject:dataDic atIndex:0];
                lanHaiArray = array;
            }
        }
        [self huoQuChangJianTiaoJian];
    }];
}




//获取创建客户的条件
- (void)huoQuChangJianTiaoJian{
    if (_customerId == nil) {
        _customerId = @"";
    }
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:[NSString stringWithFormat:@"/crmCustomer/field/%@",_customerId] andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            dataSource = [NSMutableArray array];
            NSArray *array = [info objectForKey:@"data"];
            
            for (NSInteger i = 0; i < array.count; i++) {
                NSArray *array1 = array[i];
                for (NSInteger j = 0; j < [array1 count]; j++) {
                    [dataSource addObject:array1[j]];
                }
            }
            
            if (lanHaiArray.count > 0 && _customerId.length == 0) {
                NSMutableDictionary *tempD = [NSMutableDictionary dictionary];
                [tempD setValue:@"lanHai" forKey:@"fieldName"];
                [tempD setValue:@"3" forKey:@"type"];
                [tempD setValue:@"存入" forKey:@"name"];
                [tempD setValue:@"1" forKey:@"isNull"];
//
                NSMutableArray *array = [NSMutableArray array];
                
                for (NSDictionary *dataDic in lanHaiArray) {
                    [array addObject:GetHandleString(dataDic, @"poolName")];
                }
                [tempD setValue:array forKey:@"setting"];
                [dataSource insertObject:tempD atIndex:0];
            }
            [_mainTableView reloadData];
            
            if(_customerId.length > 0){
                [self huoQuKeHuXinXi];
            }
        }
    }];
}

//获取客户信息
- (void)huoQuKeHuXinXi{
    NSString *url = [NSString stringWithFormat:@"/crmCustomer/queryById/%@",_customerId];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            keHuInfoDictionary = [info objectForKey:@"data"];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dataDic in dataSource) {
                NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:dataDic];
                if([GetHandleString(dataDic, @"fieldName") isEqualToString:@"mapAddress"]){
                    address = GetHandleString(keHuInfoDictionary, @"address");
                }else{
                    
                    if ([GetHandleString(dataDic, @"fieldName") isEqualToString:@"source"]) {
//
                        NSString *tempVa = GetHandleString(keHuInfoDictionary, GetHandleString(dataDic, @"fieldName"));
                        for (NSDictionary *tempD in [dataDic objectForKey:@"setting"]) {
                            if ([GetHandleString(tempD, @"value") isEqualToString:tempVa]) {
                                [tempDic setValue:GetHandleString(tempD, @"name") forKey:@"value"];
                            }
                        }
                    }else{
                        [tempDic setValue:GetHandleString(keHuInfoDictionary, GetHandleString(dataDic, @"fieldName")) forKey:@"value"];
                    }
                }
                [array addObject:tempDic];
            }
            dataSource = [NSMutableArray arrayWithArray:array];
            [_mainTableView reloadData];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.row]];
    
    //        `type` int(11) NOT NULL DEFAULT '1' COMMENT '字段类型 1 单行文本 2 多行文本 3 单选 4日期 5 数字 6 小数 7 手机  8 文件 9 多选 10 人员 11 附件 12 部门 13 日期时间 14 邮箱 15客户 16 商机 17 联系人 18 地图 19 产品类型 20 合同 21 回款计划',
    if([GetHandleString(dataDic, @"type") integerValue] == 2){
        XinJianKeHuWenBenYuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XinJianKeHuWenBenYuTableViewCell"];
        cell.titleLabel.text = GetHandleString(dataDic, @"name");
        if ([GetHandleString(dataDic, @"isNull") integerValue] == 1) {
            cell.readRemindLabel.text = @"*";
        }else{
            cell.readRemindLabel.text = @"";
        }
        cell.insertTextView.wzb_placeholder = [NSString stringWithFormat:@"请输入%@",GetHandleString(dataDic, @"name")];

        cell.insertTextView.text = GetHandleString(dataDic, @"value");
        cell.numLabel.text = [NSString stringWithFormat:@"%ld/%@",[GetHandleString(dataDic, @"value") length],GetHandleString(dataDic, @"maxLength")];
        cell.maxLength = [GetHandleString(dataDic, @"maxLength") integerValue];
        
        cell.textViewEndEditingBlock = ^(NSString * _Nonnull result) {
            [dataDic setValue:result forKey:@"value"];
            [dataSource replaceObjectAtIndex:indexPath.row withObject:dataDic];
            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        
        return cell;
    }
    
    //        `type` int(11) NOT NULL DEFAULT '1' COMMENT '字段类型 1 单行文本 2 多行文本 3 单选 4日期 5 数字 6 小数 7 手机  8 文件 9 多选 10 人员 11 附件 12 部门 13 日期时间 14 邮箱 15客户 16 商机 17 联系人 18 地图 19 产品类型 20 合同 21 回款计划',
    XinJianKeHuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XinJianKeHuTableViewCell"];
    cell.titleLabel.text = GetHandleString(dataDic, @"name");
         //    地区定位
         if([GetHandleString(dataDic, @"type") integerValue] == 18){
             cell.insertTextView.text = address;
         }else{
             cell.insertTextView.text = GetHandleString(dataDic, @"value");
         }
    
    if([GetHandleString(dataDic, @"type") integerValue] == 7){
        cell.insertTextView.keyboardType = UIKeyboardTypeNamePhonePad;
    }else{
        cell.insertTextView.keyboardType = UIKeyboardTypeDefault;
    }

//    if([GetHandleString(dataDic, @"type") integerValue] == 1 || [GetHandleString(dataDic, @"type") integerValue] == 7){
//        cell.xuanZeButton.hidden = YES;
//        cell.rightSpace.constant = 16;
//        cell.insertTextView.placeholder = [NSString stringWithFormat:@"请输入%@",GetHandleString(dataDic, @"name")];
//        cell.insertTextView.userInteractionEnabled = YES;
//    }else{
//        cell.xuanZeButton.hidden = NO;
//        cell.rightSpace.constant = 64;
//        cell.insertTextView.placeholder = @"请选择";
//        cell.insertTextView.userInteractionEnabled = NO;
//    }
    
    if([GetHandleString(dataDic, @"type") integerValue] == 3 || [GetHandleString(dataDic, @"type") integerValue] == 4 || [GetHandleString(dataDic, @"type") integerValue] == 13 || [GetHandleString(dataDic, @"type") integerValue] == 18){
        cell.xuanZeButton.hidden = NO;
        cell.rightSpace.constant = 64;
//        cell.insertTextView.placeholder = @"请选择";
        cell.insertTextView.placeholder = [NSString stringWithFormat:@"请选择%@",GetHandleString(dataDic, @"name")];
        if([GetHandleString(dataDic, @"name") isEqualToString:@"存入"]){
            cell.insertTextView.placeholder = @"请选择存入类型";
        }
        cell.insertTextView.userInteractionEnabled = NO;
    }else{
        cell.xuanZeButton.hidden = YES;
        cell.rightSpace.constant = 16;
        cell.insertTextView.placeholder = [NSString stringWithFormat:@"请输入%@",GetHandleString(dataDic, @"name")];
        cell.insertTextView.userInteractionEnabled = YES;
    }
    
    if ([GetHandleString(dataDic, @"isNull") integerValue] == 1) {
        cell.readRemindLabel.text = @"*";
    }else{
        cell.readRemindLabel.text = @"";
    }
    
    cell.insertTextView.delegate = self;
    cell.insertTextView.tag = indexPath.row*100;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = dataSource[indexPath.row];
    if([GetHandleString(dataDic, @"type") integerValue] == 2){
        return 162;
    }
    return 102;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger row = textField.tag/100;
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[row]];

    if([GetHandleString(dataDic, @"type") integerValue] == 7){
        // 获取当前文本框中的文本
        NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        // 设置最大字符长度
        NSUInteger maxLength = 11; // 例如限制输入长度为10个字符
        
        // 检查是否超过最大长度
        if (newText.length <= maxLength) {
            return YES; // 允许输入
        } else {
            return NO; // 超过最大长度，禁止输入
        }
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [textField resignFirstResponder];
    
    NSInteger row = textField.tag/100;
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[row]];
    
    [dataDic setValue:textField.text forKey:@"value"];
 
    [dataSource replaceObjectAtIndex:row withObject:dataDic];
    [_mainTableView reloadData];
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.row]];
    
    if([GetHandleString(dataDic, @"type") integerValue] == 3){
        BRStringPickerView *datePickerView = [[BRStringPickerView alloc]init];
        datePickerView.pickerMode = BRStringPickerComponentSingle;
        datePickerView.title = @"";
        NSMutableArray *array = [NSMutableArray arrayWithArray:[dataDic objectForKey:@"setting"]];
        if ([[dataDic objectForKey:@"fieldName"] isEqualToString:@"source"]) {
            
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *tempD in array) {
                if ([GetHandleString(tempD, @"name") isEqualToString:GetHandleString(dataDic, @"value")]) {
                    if ([GetHandleString(tempD, @"value") isEqualToString:@"app"]) {
                        [ZZPUtils showWarning:@"app来源无法更改"];
                        return;
                    }
                }
                [tempArray addObject:GetHandleString(tempD, @"name")];
            }
            array = tempArray;
        }
        datePickerView.dataSourceArr = array;
        datePickerView.selectValue = GetHandleString(dataDic, @"value");
       
        datePickerView.resultModelBlock = ^(BRResultModel *resultModel) {
            NSLog(@"选择的索引：%@", @(resultModel.index));
            NSLog(@"选择的值：%@", resultModel.value);
            
            [dataDic setValue:resultModel.value forKey:@"value"];
            
            [dataSource replaceObjectAtIndex:indexPath.row withObject:dataDic];
            [_mainTableView reloadData];
            
        };
        
        BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
        customStyle.pickerColor = [UIColor whiteColor];
        customStyle.selectRowTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarColor = [UIColor whiteColor];
        customStyle.titleTextColor = [UIColor whiteColor];
        customStyle.cancelTextColor = rgba(153, 153, 153, 1);
        customStyle.doneTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarHeight = 48;
        customStyle.titleTextFont = [UIFont systemFontOfSize:18];
        datePickerView.pickerStyle = customStyle;
        customStyle.topCornerRadius = 10;
        customStyle.hiddenTitleLine = YES;
        customStyle.separatorColor = rgba(223, 229, 242, 1);
        customStyle.separatorHeight = 0.5;
        customStyle.rowHeight = 64;
        
        [datePickerView show];
        
        
    }else if([GetHandleString(dataDic, @"type") integerValue] == 18){
        BRAddressPickerView *addressPickerView = [[BRAddressPickerView alloc]init];
        addressPickerView.pickerMode = BRAddressPickerModeArea;
        addressPickerView.title = @"";
        addressPickerView.isAutoSelect = NO;
        addressPickerView.selectIndexs = self.addressSelectIndexs;
        addressPickerView.resultBlock = ^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
            self.addressSelectIndexs = @[@(province.index), @(city.index), @(area.index)];
            address = [NSString stringWithFormat:@"%@%@%@",province.name,city.name,area.name];
            [_mainTableView reloadData];
        };
        BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
        customStyle.pickerColor = [UIColor whiteColor];
        customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
        customStyle.titleBarColor = [UIColor whiteColor];
        customStyle.titleTextColor = [UIColor whiteColor];
        customStyle.cancelTextColor = rgba(153, 153, 153, 1);
        customStyle.doneTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarHeight = 48;
        customStyle.titleTextFont = [UIFont systemFontOfSize:18];
        addressPickerView.pickerStyle = customStyle;
        customStyle.topCornerRadius = 10;
        customStyle.hiddenTitleLine = YES;
        customStyle.separatorColor = rgba(223, 229, 242, 1);
        customStyle.separatorHeight = 0.5;
        customStyle.rowHeight = 64;
        
        [addressPickerView show];
    }else if([GetHandleString(dataDic, @"type") integerValue] == 13 || [GetHandleString(dataDic, @"type") integerValue] == 4){
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
        datePickerView.pickerMode = BRDatePickerModeDate;
        datePickerView.title = @"";
        datePickerView.minDate = nil;
        datePickerView.maxDate = nil;
        datePickerView.isAutoSelect = NO;

        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
       
            NSLog(@"selectValue=%@", selectValue);
            NSLog(@"selectDate=%@", selectDate);
            NSLog(@"---------------------------------");
            [dataDic setValue:selectValue forKey:@"value"];
            [dataSource replaceObjectAtIndex:indexPath.row withObject:dataDic];
            [_mainTableView reloadData];
        };
     
        
        BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
        customStyle.pickerColor = [UIColor whiteColor];
        customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
        customStyle.titleBarColor = [UIColor whiteColor];
        customStyle.titleTextColor = [UIColor whiteColor];
        customStyle.cancelTextColor = rgba(153, 153, 153, 1);
        customStyle.doneTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarHeight = 48;
        customStyle.titleTextFont = [UIFont systemFontOfSize:18];
        datePickerView.pickerStyle = customStyle;
        customStyle.topCornerRadius = 10;
        customStyle.hiddenTitleLine = YES;
        customStyle.separatorColor = rgba(223, 229, 242, 1);
        customStyle.separatorHeight = 0.5;
        customStyle.rowHeight = 64;

        [datePickerView show];
    }
    
}

//新建客户
- (IBAction)xinJian:(UIButton *)sender {
    [self.view endEditing:YES];
    
    for (NSInteger j = 0; j < [dataSource count]; j++) {
        if([GetHandleString(dataSource[j], @"value") length] == 0 && [GetHandleString(dataSource[j], @"isNull") integerValue] == 1){
//            if([GetHandleString(dataSource[j], @"formType") isEqualToString:@"text"] || [GetHandleString(dataSource[j], @"formType") isEqualToString:@"mobile"]){
//                [ZZPUtils showWarning:[NSString stringWithFormat:@"请先输入%@",GetHandleString(dataSource[j], @"name")]];
//                
//            }else{
//                [ZZPUtils showWarning:[NSString stringWithFormat:@"请先选择%@",GetHandleString(dataSource[j], @"name")]];
//            }
            
            if([GetHandleString(dataSource[j], @"type") integerValue] == 3 || [GetHandleString(dataSource[j], @"type") integerValue] == 4 || [GetHandleString(dataSource[j], @"type") integerValue] == 13 || [GetHandleString(dataSource[j], @"type") integerValue] == 18){
                [ZZPUtils showWarning:[NSString stringWithFormat:@"请先选择%@",GetHandleString(dataSource[j], @"name")]];
            }else{
                [ZZPUtils showWarning:[NSString stringWithFormat:@"请先输入%@",GetHandleString(dataSource[j], @"name")]];
            }
            return;
        }
    }
    
    
    
    NSMutableArray *temp = [NSMutableArray array];
    
    for (NSInteger j = 0; j < [dataSource count]; j++) {
        NSDictionary *dataDic = dataSource[j];
        if([GetHandleString(dataDic, @"fieldId") length] > 0){
            NSMutableDictionary *linShi = [NSMutableDictionary dictionary];
            [linShi setValue:GetHandleString(dataDic, @"fieldName") forKey:@"fieldName"];
            [linShi setValue:GetHandleString(dataDic, @"fieldType") forKey:@"fieldType"];
            [linShi setValue:GetHandleString(dataDic, @"name") forKey:@"name"];
            [linShi setValue:GetHandleString(dataDic, @"type") forKey:@"type"];
            [linShi setValue:GetHandleString(dataDic, @"fieldId") forKey:@"fieldId"];
            if ([[dataDic objectForKey:@"fieldName"] isEqualToString:@"source"]) {
                for (NSDictionary *tempD in [dataDic objectForKey:@"setting"]) {
                    if ([GetHandleString(tempD, @"name") isEqualToString:GetHandleString(dataDic, @"value")]) {
                        [linShi setValue:GetHandleString(tempD, @"value") forKey:@"value"];
                    }
                }
            }else{
                [linShi setValue:GetHandleString(dataDic, @"value") forKey:@"value"];
            }
            
            [temp addObject:linShi];
        }
    }
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:temp forKey:@"field"];
    
    NSMutableDictionary *entity = [NSMutableDictionary dictionary];
    [entity setValue:[self huoQuXuYaoWithName:@"customerName" andArray:temp] forKey:@"customerName"];
    [entity setValue:[self huoQuXuYaoWithName:@"mobile" andArray:temp] forKey:@"mobile"];
    [entity setValue:[self huoQuXuYaoWithName:@"remark" andArray:temp] forKey:@"remark"];
    [entity setValue:address forKey:@"address"];
    [entity setValue:@"1" forKey:@"detailAddress"];
    
    NSString *url = @"/crmCustomer/add";
    if(_customerId.length > 0){
        [entity setValue:_customerId forKey:@"customerId"];
        [entity setValue:GetHandleString(keHuInfoDictionary, @"batchId") forKey:@"batchId"];
        url = @"/crmCustomer/update";
    }
    
    if (_shiBuShiZongLanKeHu) {
        url = @"/crmCustomerAll/addOrUpdate";
    }
    
//
    if(lanHaiArray.count > 0){
        NSString *poolId;
        NSDictionary *dataDic = dataSource.firstObject;
        NSString *lanHaiString = GetHandleString(dataDic, @"value");
        for (NSDictionary *temp in lanHaiArray) {
            if ([GetHandleString(temp, @"poolName") isEqualToString:lanHaiString]) {
                poolId = GetHandleString(temp, @"poolId");
            }
        }
        [paraDic setValue:poolId forKey:@"poolId"];
    }


    [paraDic setValue:entity forKey:@"entity"];
    
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            if(_customerId.length > 0){
                [ZZPUtils showWarning:@"编辑成功"];
            }else{
                [ZZPUtils showWarning:@"创建成功"];
            }
            
            if(_manageClick){
                _manageClick(0);
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    
}

- (NSString *)huoQuXuYaoWithName:(NSString *)name andArray:(NSArray *)array{
    NSString *result = nil;
    for (NSInteger j = 0; j < [array count]; j++) {
        NSDictionary *dataDic = array[j];
        if([GetHandleString(dataDic, @"fieldName") isEqualToString:name]){
            result = GetHandleString(dataDic, @"value");
            break;
        }
    }
    return result;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end




